<?php

namespace App\Http\Controllers;

use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Container\Attributes\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $data = $request->validate([
            'email' => ['required', 'email', 'exists:users'],
            'password' => ['required', 'string'],
        ]);
        $user = User::where('email', $data['email'])->first();
        if (! $user || ! Hash::check($data['password'], $user->password)) {
            return response([
                'errors' => [
                    'email' => ['邮箱或密码错误']
                ]
            ], 401);
        }
        $token = $user->createToken($user->name)->plainTextToken;
        return response([
            'user' => UserResource::make($user),
            'token' => $token
        ], 200);
    }
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string'],
            'email' => ['required', 'email', 'unique:users'],
            'password' => ['required', 'string', 'confirmed'],
        ], [
            'email.unique' => '邮箱已被注册',
            'password.confirmed' => '两次密码不一致',
            'password.required' => '密码不能为空',
            'email.required' => '邮箱不能为空',
            'name.required' => '用户名不能为空',
            'email.email' => '邮箱格式不正确',
        ]);
        $user = User::create($data);
        $token = $user->createToken($data['name'])->plainTextToken;
        return response([
            'user' => UserResource::make($user),
            'token' => $token
        ], 200);
    }
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response([
            'message' => '登出成功'
        ], 200);
    }
}
